package com.walkline.dianping;

import net.rim.device.api.crypto.MD5Digest;
import net.rim.device.api.crypto.SHA1Digest;

public class Digest
{
	public static String md5Hash(String str)
	{
		MD5Digest md5 = new MD5Digest();
		byte[] bytes = str.getBytes();

		md5.reset();
		md5.update(bytes, 0, bytes.length);

		return new String(convertToHexStr(md5.getDigest())).toUpperCase();
	}

	public static String md5Hash(byte[] bytes)
	{
		MD5Digest md5 = new MD5Digest();

		md5.reset();
		md5.update(bytes, 0, bytes.length);
		
		return new String(convertToHexStr(md5.getDigest())).toUpperCase();
	}

	public static String sha1Hash(String string)
	{
		SHA1Digest sha1 = new SHA1Digest();
		byte[] bytes = string.getBytes();

		sha1.reset();
		sha1.update(bytes, 0, bytes.length);

		return new String(convertToHexStr(sha1.getDigest())).toUpperCase();
	}

	public static String sha1Hash(byte[] bytes)
	{
		SHA1Digest sha1 = new SHA1Digest();

		sha1.reset();
		sha1.update(bytes, 0, bytes.length);

		return new String(convertToHexStr(sha1.getDigest())).toUpperCase();
	}

	private static String convertToHexStr(byte[] data)
	{
		StringBuffer buf = new StringBuffer();
		
		for (int i=0; i<data.length; i++)
		{
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;

			do
			{
				if ((0 <= halfbyte) && (halfbyte <= 9))
				{
					buf.append((char) ('0' + halfbyte));					
				} else {
					buf.append((char) ('a' + (halfbyte - 10)));
				}
				
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		
		return buf.toString();
	}
}